//
//  HRSelectedFriendsViewController.m
//  SpeedDating
//
//  Created by ISU1 on 17/2/8.
//  Copyright © 2017年 isu. All rights reserved.
//

#import "FriendRemindWhoController.h"
#import "SDContactModel.h"
#import "SDContactsTableViewCell.h"
#import "FriendRemindWhocell.h"

@interface FriendRemindWhoController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic,strong) NSMutableArray *sectionArray;

@property (nonatomic, strong) NSMutableArray *sectionTitlesArray;

@property (nonatomic, weak) UIView *navBarView;

@end

@implementation FriendRemindWhoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setTitle:_titleString];
    UIButton *commitBtn = [UIButton new];
    [commitBtn setTitle:@"确认" forState:UIControlStateNormal];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    commitBtn.frame = CGRectMake(0, 0, 40, 40);
    commitBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [commitBtn addTarget:self action:@selector(clickRightButton) forControlEvents:UIControlEventTouchUpInside];
    [commitBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:commitBtn];

    _userArray = @[].mutableCopy;
    
    [self sendRequest];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0, KScreenWidth, 40)];
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索";
    [self.view addSubview:searchBar];
}

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

- (void)clickRightButton {

    NSMutableArray *array = @[].mutableCopy;
    for (NSDictionary *dic in self.userArray) {
        if ([self.addUserArray containsObject:dic[@"wid"]]) {
            [array addObject:dic];
        }
    }
    if (self.selectedFriend) {
        self.selectedFriend(array, self.addUserArray);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)sendRequest {
    WEAKSELF
    [HQHttpManager myFriendListWithUserid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _userArray = @[].mutableCopy;
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.sectionArray removeAllObjects];
            [weakSelf.sectionTitlesArray removeAllObjects];
            NSArray *array = resultDic[@"res"];
            weakSelf.userArray = array.mutableCopy;
            [weakSelf genDataWithArray:_userArray];
        }
    }];
}

- (void)genDataWithArray:(NSArray *)array {
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        SDContactModel *model = [SDContactModel new];
        model.name = dic[@"nickName"];
        model.imageName = dic[@"photo"];
        model.wid = dic[@"wid"];
        [self.dataArray addObject:model];
    }
    [self setUpTableSection];
}

- (void)setUpTableSection {
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSUInteger numberOfSections = [[collation sectionTitles] count];
    NSMutableArray *newSectionArray =  [[NSMutableArray alloc]init];
    for (NSUInteger index = 0; index<numberOfSections; index++) {
        [newSectionArray addObject:[[NSMutableArray alloc]init]];
    }
    for (SDContactModel *model in self.dataArray) {
        NSUInteger sectionIndex = [collation sectionForObject:model collationStringSelector:@selector(name)];
        [newSectionArray[sectionIndex] addObject:model];
    }
    for (NSUInteger index=0; index<numberOfSections; index++) {
        NSMutableArray *personsForSection = newSectionArray[index];
        NSArray *sortedPersonsForSection = [collation sortedArrayFromArray:personsForSection collationStringSelector:@selector(name)];
        newSectionArray[index] = sortedPersonsForSection;
    }
    NSMutableArray *temp = [NSMutableArray new];
    self.sectionTitlesArray = [NSMutableArray new];
    [newSectionArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
        if (arr.count == 0) {
            [temp addObject:arr];
        } else {
            [self.sectionTitlesArray addObject:[collation sectionTitles][idx]];
        }
    }];
    [newSectionArray removeObjectsInArray:temp];
    NSMutableArray *operrationModels = [NSMutableArray new];
    [newSectionArray insertObject:operrationModels atIndex:0];
    [self.sectionTitlesArray insertObject:@"" atIndex:0];
    self.sectionArray = newSectionArray;
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.view).offset(40);
        }];
    }
    [_tableView reloadData];
}

#pragma mark - tableview delegate and datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionTitlesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.sectionArray[section] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"SelectFriendCell";
    FriendRemindWhocell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[FriendRemindWhocell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    SDContactModel *model = self.sectionArray[section][row];
    cell.model = model;
    if ([_addUserArray containsObject:model.wid]) {
        cell.isSelect = YES;
    } else {
        cell.isSelect = NO;
    }
    return cell;
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [self.sectionTitlesArray objectAtIndex:section];
}


- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sectionTitlesArray;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.row);
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    SDContactModel *model = self.sectionArray[section][row];
    if ([_addUserArray containsObject:model.wid]) {
        [_addUserArray removeObject:model.wid];
    } else {
        [_addUserArray addObject:model.wid];
    }
    [_tableView reloadData];
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"......");
    [self.view endEditing:YES];
    NSMutableArray *array = @[].mutableCopy;
    [self.dataArray removeAllObjects];
    [self.sectionArray removeAllObjects];
    [self.sectionTitlesArray removeAllObjects];
    for (NSDictionary *dic in _userArray) {
        if ([dic[@"nickName"] rangeOfString:searchBar.text].location != NSNotFound) {
            [array addObject:dic];
        }
    }
    [self genDataWithArray:array];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (!searchText.length) {
        [self.dataArray removeAllObjects];
        [self.sectionArray removeAllObjects];
        [self.sectionTitlesArray removeAllObjects];
        [self genDataWithArray:_userArray];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

@end
